﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MineBoxRelease.Core;
using MineBoxRelease.Core.View;
using MineBoxRelease.Custom;
using MineBoxRelease.View;
using MineBoxRelease.Win;

namespace MineBoxRelease
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        #region 变量
        private const string xmlPath = "xml/";

        #endregion
        public MainWindow()
        {
            InitializeComponent();
            InitializeData();
            InitializeEvent();
        }

        //初始化数据
        protected void InitializeData()
        {
            LoadXml();

            //初始化“新建”标签
            defaultTab = new DefaultTabItem();
            DefaultView view = new DefaultView();
            defaultTab.View = view;
            view.Tab = defaultTab;
            view.ViewCreated += DefaultView_ViewCreated;
            UpdateDefaultTab();

            //选择第一个标签
            var tabFirst = pnTab.Children[0] as DefaultTabItem;
            if (tabFirst == null) return;
            tabFirst.IsChecked = true;
        }

        //初始化事件
        protected void InitializeEvent()
        {
            MouseLeftButtonDown += (s, e) => DragMove();
            btnMenu.Click += (s, e) =>
            {
                if (btnMenu.IsChecked == true)
                    gdMenu.Visibility = Visibility.Visible;
                else
                    gdMenu.Visibility = Visibility.Collapsed;

            };
            btnAbout.Click += (s, e) => new AboutWindow().Show();
            btnExit.Click += (s, e) =>
            {
                var animation = new DoubleAnimation() { To = 0, Duration = TimeSpan.FromSeconds(0.5) };
                Storyboard.SetTarget(animation, this);
                Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity"));
                Storyboard sb = new Storyboard();
                sb.Children.Add(animation);
                sb.Completed += (ss, ee) => Application.Current.Shutdown();
                sb.Begin();
            };
            btnMin.Click += (s, e) => this.WindowState = WindowState.Minimized;
        }

        #region 功能

        private DefaultTabItem defaultTab;
        //更新“新建”标签
        private void UpdateDefaultTab()
        {
            //如果已经存在“新建”标签，并且标签数大于最大标签数，则移除“新建”标签，不可再进行新建
            if (pnTab.Children.Contains(defaultTab) && pnTab.Children.Count > 9)
                pnTab.Children.Remove(defaultTab);

            //如果不存在“新建”标签，并且标签数不足最大标签数，则插入“新建”标签
            else if (!pnTab.Children.Contains(defaultTab) && pnTab.Children.Count < 9)
                pnTab.Children.Add(defaultTab);
        }

        void DefaultView_ViewCreated(object sender, ViewCreatedEventArgs e)
        {
            CloseableTabItem tab = new CloseableTabItem();
            BaseView view = ViewManager.CreateView(e.ViewName, e.Title);
            tab.View = view;
            tab.Content = ViewManager.GetRegeditItemByName(e.ViewName).ViewIcon;
            view.Tab = tab;
            pnTab.Children.Insert(pnTab.Children.Count - 1, tab);
            pnTab.UpdateLayout();
            UpdateDefaultTab();
            tab.IsChecked = true;
        }

        //加载并解析xml文件
        private void LoadXml()
        {
            ViewXmlConfiguration.Load();
            foreach (int id in ViewXmlConfiguration.Data.Keys)
            {
                string path = ViewXmlConfiguration.Data[id];
                BaseView view = ViewManager.CreateViewFromXml(path);
                view.Id = id;
                CloseableTabItem tab = new CloseableTabItem();
                tab.Content = ViewManager.GetRegeditItemByType(view.GetType()).ViewIcon;
                tab.View = view;
                view.Tab = tab;
                pnTab.Children.Add(tab);
            }
        }

        private void TabChange(DefaultTabItem tab)
        {
            //三角标志移动动画
            double newTop = tab.TransformToAncestor(pnTab).Transform(new Point(0, 0)).Y + tab.Height / 2 - 6;
            Debug.WriteLine(newTop);
            ThicknessAnimation animation = new ThicknessAnimation
            {
                To = new Thickness(0, newTop, 0, 0),
                Duration = TimeSpan.FromSeconds(0.2),
                EasingFunction = new CircleEase() { EasingMode = EasingMode.EaseOut }
            };
            Storyboard.SetTarget(animation, tabFlag);
            Storyboard.SetTargetProperty(animation, new PropertyPath("Margin"));
            Storyboard storyboard = new Storyboard();
            storyboard.Children.Add(animation);
            storyboard.Begin();

            //视图更新
            BaseView view = tab.View;
            if (view == null) return;
            gdBody.Children.Clear();
            gdBody.Children.Add(view);
        }

        #endregion

        private void TabItem_Checked(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("Checked");
            DefaultTabItem tabItem = sender as DefaultTabItem;
            if (tabItem == null) return;
            TabChange(tabItem);
        }

        private void TabItem_Closing(object sender, RoutedEventArgs e)
        {
            var tab = sender as CloseableTabItem;
            if (tab == null) return;
            tab.IsChecked = true;
            //todo:自定义MessageBox窗口样式
            if (MessageBox.Show("标签关闭后数据将永久性关闭，是否继续？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.No) return;
            int index = pnTab.Children.IndexOf(tab);
            //准备选择新标签
            DefaultTabItem checkTab = null;
            if (index > 0)
                checkTab = pnTab.Children[index - 1] as DefaultTabItem;
            else if (pnTab.Children.Count > index + 1)
                checkTab = pnTab.Children[index + 1] as DefaultTabItem;
            ViewXmlConfiguration.Remove(tab.View);
            pnTab.Children.Remove(tab);
            pnTab.UpdateLayout();
            UpdateDefaultTab();
            if (checkTab != null) checkTab.IsChecked = true;
        }
    }
}
